package com.borball.store.comp;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.sql.Timestamp;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.ListSelectionModel;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.table.TableRowSorter;

import com.borball.store.dao.MStoreLogDAO;
import com.borball.store.dao.MaterailStoreDAO;
import com.borball.store.domain.MStoreLog;
import com.borball.store.domain.Material;
import com.borball.store.domain.MaterialStore;
import com.borball.store.domain.User;
import com.borball.store.util.MaterialUtils;
import com.borball.store.util.StoreChangeActions;
import com.borball.store.util.UserUtils;

import craky.component.CommonTableModel;
import craky.componentc.JCButton;
import craky.componentc.JCComboBox;
import craky.componentc.JCLabel;
import craky.componentc.JCMessageBox;
import craky.componentc.JCNumberField;
import craky.componentc.JCScrollTable;
import craky.componentc.JCScrollText;
import craky.componentc.JCTable;
import craky.componentc.JCTableHeader;
import craky.keeper.EmptyComponent;
import craky.keeper.KeeperApp;
import craky.keeper.KeeperPane;
import craky.layout.LineLayout;

public class MaterialInPane extends KeeperPane {

	private static final long serialVersionUID = 2583431180094797757L;

	protected JCTable table;
	protected List<MaterialStore> data;
	protected User currentUser;
	protected CommonTableModel<MaterialStore> model;
	private static final String[] COLUMNS_NAME = { "类型", "数量", "单位", "上次入库时间" };
	protected JComponent bottom, center;
	private JCButton btnInsert;
	protected JCNumberField cpAmount;
	protected JCScrollText cpMemo;
	protected JCComboBox cpType, cpUser;
	protected JComponent ecAmount, ecType, ecMemo, ecUser;
	protected Action insertAction;
	private MaterailStoreDAO dao;
	protected KeeperApp keeper;
	public MaterialInPane(KeeperApp keeper) {
		this.keeper = keeper;
		this.currentUser = keeper.getCurrentUser();
		dao = new MaterailStoreDAO();
		loadData();
		initActions();
		initUI();
	}

	private void initActions() {
		insertAction = new AbstractAction("入库") {
			private static final long serialVersionUID = 5056698643009336063L;

			public void actionPerformed(ActionEvent e) {
				insertOrModify(true);
			}
		};

	}

	public void insertOrModify(boolean insert) {
		if (insert) {
			if (checkNull()) {
				MaterialStore store = dao.findByPK(cpType.getSelectedItem());
				int originalStore = 0;
				int currentStore = 0;
				if (store == null) {
					store = new MaterialStore();
					currentStore = Integer.valueOf(cpAmount.getText());
					store.setName(cpType.getSelectedItem().toString());
					store.setAmount(currentStore);
					store.setUnit(MaterialUtils.getInstance().getByName(cpType.getSelectedItem().toString()).getUnit());

					store.setModified(new Timestamp(System.currentTimeMillis()));
					dao.add(store);
				} else {
					originalStore = store.getAmount();
					currentStore = originalStore + Integer.valueOf(cpAmount.getText());
					store.setAmount(currentStore);
					store.setModified(new Timestamp(System.currentTimeMillis()));

					dao.updateStore(store);

				}
				// TODO add change log
				addLog(StoreChangeActions.IN, cpType.getSelectedItem().toString(), Integer.valueOf(cpAmount.getText()), cpMemo.getEditor()
						.getText(), cpUser.getSelectedItem().toString(), currentUser.getName());

				JCMessageBox.createInformationMessageBox(keeper.getMainFrame(), "入库成功",
						"入库成功,原有库存:" + originalStore + ",现库存:" + currentStore).open();

				loadData();
				model.delAllRow();
				model.setDataList(data);
				model.getTable().repaint();
				model.refreshRowOnView(0);

				reset();
			}
		}

	}

	private boolean checkNull() {
		if (cpType.getSelectedItem() == null || "".equals(cpAmount.getText()) || cpUser.getSelectedItem() == null) {

			JCMessageBox.createErrorMessageBox(keeper.getMainFrame(), "必填项为空", "请输入所有必填项").open();

			cpType.requestFocus();
			return false;
		}
		return true;
	}

	private void addLog(StoreChangeActions action, String material, Integer amount, String memo, String user, String operator) {
		MStoreLog log = new MStoreLog();
		log.setAction(action.getMessage());
		log.setAmount(amount);
		log.setUser(user);
		log.setOperator(operator);
		log.setMaterial(material);
		log.setCreated(new Timestamp(System.currentTimeMillis()));
		log.setMemo(memo);
		MStoreLogDAO dao = new MStoreLogDAO();
		dao.add(log);
	}

	private void reset() {
		cpAmount.setText(null);
		cpType.setSelectedIndex(-1);
		//cpUser.setSelectedIndex(-1);
		cpMemo.getEditor().setText(null);
	}

	private void loadData() {
		data = dao.findAll();
		keeper.refreshStatus();
	}

	private void initUI() {
		btnInsert = new JCButton(insertAction);
		btnInsert.setPreferredSize(new Dimension(75, 30));
		EmptyComponent centerParent = new EmptyComponent();
		setLayout(new BorderLayout());
		centerParent.setLayout(new BorderLayout(0, 3));
		createCenter();
		createBottom();

		this.add(centerParent, BorderLayout.CENTER);

		if (center != null) {
			centerParent.add(center, BorderLayout.CENTER);
		}

		if (bottom != null) {
			centerParent.add(bottom, BorderLayout.NORTH);
		}
		
		loadTypes();
		loadUsers();
	}

	private void loadUsers() {
		List<User> users = UserUtils.getInstance().getAllUsers();
	
		cpUser.removeAllItems();
		for (User user : users) {
			cpUser.addItem(user.getName());
		}
		cpUser.setSelectedItem(keeper.getCurrentUser());
		
	}

	private void loadTypes() {
		List<Material> types = MaterialUtils.getInstance().getAll();
		
		Object oldSelType = cpType.getSelectedItem();
		
		cpType.removeAllItems();
		for (Material matetailType : types) {
			cpType.addItem(matetailType.getName());
		}
		cpType.setSelectedItem(oldSelType);

	}

	private JComponent createBottom() {
		int leftGap = 0;
		int rightGap = 0;
		bottom = new EmptyComponent();
		bottom.setBorder(new CompoundBorder(new EmptyBorder(0, leftGap, 0, rightGap), new LineBorder(new Color(84, 165,
				213))));
		bottom.setPreferredSize(new Dimension(-1, 77));
		bottom.setLayout(new BorderLayout());
		bottom.add(createDetailComponent(), BorderLayout.CENTER);

		EmptyComponent buttonContainer = new EmptyComponent();
		buttonContainer.setLayout(new LineLayout(3, 0, 5, 0, 3, LineLayout.TRAILING, LineLayout.TRAILING,
				LineLayout.VERTICAL));
		buttonContainer.setPreferredSize(new Dimension(85, -1));

		buttonContainer.add(btnInsert, LineLayout.END_FILL);
		bottom.add(buttonContainer, BorderLayout.EAST);

		return bottom;

	}

	private Component createDetailComponent() {
		EmptyComponent ec = new EmptyComponent();
		EmptyComponent firstRow = new EmptyComponent();
		EmptyComponent secondRow = new EmptyComponent();
		JCLabel lbAmount = new JCLabel("数量(*)");
		JCLabel lbType = new JCLabel("类型(*)");
//		JCLabel lbUnit = new JCLabel("单位");
		JCLabel lbUser = new JCLabel("入库人员(*)");
		JCLabel lbMemo = new JCLabel("备注");
		Border border = new EmptyBorder(0, 0, 0, 5);
		cpAmount = new JCNumberField(0, 0, 99999);
		cpMemo = new JCScrollText();
		cpType = new JCComboBox();
		cpUser = new JCComboBox();
		cpAmount.setNonNegative(true);
		cpMemo.getEditor().setLineWrap(true);

		firstRow.setLayout(new BoxLayout(firstRow, BoxLayout.X_AXIS));
		firstRow.setPreferredSize(new Dimension(-1, 25));
		secondRow.setLayout(new GridLayout(1, 2));

		firstRow.add(ecType = createTitledComponent(lbType, cpType, border, 3));
		firstRow.add(ecAmount = createTitledComponent(lbAmount, cpAmount, border, 3));
//		firstRow.add(ecUnit = createTitledComponent(lbUnit, cpUnit, border, 3));
		firstRow.add(ecUser = createTitledComponent(lbUser, cpUser, null, 3));
		firstRow.setPreferredSize(new Dimension(-1, 24));

		secondRow.add(ecMemo = createTitledComponent(lbMemo, cpMemo, border, 3));
		ec.setLayout(new BorderLayout(0, 5));
		ec.setBorder(new EmptyBorder(3, 5, 2, 2));
		ec.add(firstRow, BorderLayout.NORTH);
		ec.add(secondRow, BorderLayout.CENTER);
		ecAmount.setPreferredSize(new Dimension(50, -1));
		ecType.setPreferredSize(new Dimension(28, -1));
//		ecUnit.setPreferredSize(new Dimension(28, -1));
		ecUser.setPreferredSize(new Dimension(40, -1));

		return ec;
	}


	@Override
	public String getType() {
		return "元件入库";
	}

	private JComponent createTitledComponent(JComponent titleComponent, JComponent component, Border border, int hgap) {
		EmptyComponent ec = new EmptyComponent();
		ec.setBorder(border);
		ec.setLayout(new BorderLayout(hgap, 0));
		ec.add(component, BorderLayout.CENTER);

		if (titleComponent != null) {
			ec.add(titleComponent, BorderLayout.WEST);
		}

		return ec;
	}

	protected JComponent createCenter() {
		final Class<?>[] columnsClass = { String.class, Integer.class, String.class, Timestamp.class };
		final String[] getMethodsName = { "getName", "getAmount", "getUnit", "getModified" };
		final String[] setMethodsName = { "setName", "setAmount", "setUnit", "setModified" };
		final int[] columnsPreferredWidth = { 120, 60, 60 };
		EmptyComponent ec = new EmptyComponent();
		JCScrollTable scTable = new JCScrollTable();
		table = scTable.getTable();
		model = new CommonTableModel<MaterialStore>(table, COLUMNS_NAME, columnsClass, getMethodsName, setMethodsName,
				data);
		TableRowSorter<CommonTableModel<MaterialStore>> sorter = new TableRowSorter<CommonTableModel<MaterialStore>>(
				model);

		scTable.setAlpha(0.0f);
		scTable.setColumnControlEnabled(false);

		ec.setLayout(new BorderLayout());
		ec.add(scTable, BorderLayout.CENTER);
		table.setModel(model);
		table.setDragEnabled(false);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.setRowSorter(sorter);
		table.setRendererOpaque(false);
		((JCTableHeader) table.getTableHeader()).setShowPopupMenu(false);

		for (int i = 0; i < columnsPreferredWidth.length; i++) {
			table.getColumnModel().getColumn(i).setPreferredWidth(columnsPreferredWidth[i]);
		}

		return center = ec;
	}

	@Override
	public void refresh() {
		loadData();
		model.delAllRow();
		model.setDataList(data);
		model.getTable().repaint();
		model.refreshRowOnView(0);
		
		loadTypes();
		loadUsers();
//		loadUnits();
	}

}
